package widget_tree

import (
	widgetcommon "clientDemo/ui/fyne_ui/widget/interface"
	"fmt"
	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/widget"
)

type TreeNodeInfo struct {
	id           widget.TreeNodeID
	branch       bool
	ptrAsString  string
	child        []*TreeNodeInfo
	node         widgetcommon.IWidgetItem
	name         string              // 显示名称
	childName    []string            // 子对象显示名称
	childObjName []widget.TreeNodeID // tree对象名称

	treeNode fyne.CanvasObject
}

func NewWidgetTreeEditor(name string) *WidgetTreeEditor {
	o := &WidgetTreeEditor{
		name: name,
	}
	o.tabItem = &container.TabItem{}
	o.tabItem.Text = o.name
	o.tabItem.Content = o.mainScroll

	o.treeRoot = widget.NewTree(
		func(id widget.TreeNodeID) []widget.TreeNodeID {
			switch id {
			case "":
				return []widget.TreeNodeID{"a", "b", "c", "d", "e", "f"}
			case "a":
				return []widget.TreeNodeID{"a1", "a2"}
			case "b":
				return []widget.TreeNodeID{"b1", "b2"}
			}
			return []string{}
		},
		func(id widget.TreeNodeID) bool {
			return id == "" || id == "a" || id == "b"
		},
		func(branch bool) fyne.CanvasObject {
			if branch {
				return widget.NewLabel("分支模板")
			}
			return widget.NewEntry()
		},
		func(id widget.TreeNodeID, branch bool, o fyne.CanvasObject) {
			//text := id
			text := "节点"
			if branch {
				text += " (分支)"
				o.(*widget.Label).SetText(text)
			} else {
				text += " (叶子)"
				o.(*widget.Entry).SetText(id)
			}
		})

	o.tabItem.Content = o.treeRoot
	o.mainScroll = container.NewScroll(
		o.treeRoot,
	)
	o.tabItem.Content = o.mainScroll
	return o
}

type WidgetTreeEditor struct {
	tabItem    *container.TabItem // 页签
	mainScroll *container.Scroll  // 页签下滚动页面
	treeRoot   *widget.Tree       // 页签Tree
	name       string

	// 新增字段用于与属性编辑器联动
	onNodeDoubleClicked func(widgetcommon.IWidgetItem) // 双击节点时的回调
}

func (e *WidgetTreeEditor) GetTabItem() *container.TabItem {
	return e.tabItem
}

// SetOnNodeDoubleClicked 设置双击节点时的回调函数
func (e *WidgetTreeEditor) SetOnNodeDoubleClicked(callback func(widgetcommon.IWidgetItem)) {
	e.onNodeDoubleClicked = callback
}

func (e *WidgetTreeEditor) UpdateTreeItem(widgetItem widgetcommon.IWidgetItem) {
	// 更新树的数据

	var allTreeMap = map[string]*TreeNodeInfo{}
	fn := func(id widget.TreeNodeID) []widget.TreeNodeID {
		if widgetItem == nil {
			return []widget.TreeNodeID{}
		}
		all, ok := allTreeMap[id]
		if ok {
			return all.childObjName
		}
		if id == "" {
			ptrRootAsString := fmt.Sprintf("%p", widgetItem)
			nodeRootObj := &TreeNodeInfo{
				id:          id,
				ptrAsString: ptrRootAsString,
				name:        widgetItem.GetName(),
				node:        widgetItem,
			}
			var AddChildFun func(parentTreeNodeInfo *TreeNodeInfo, parentWidgetItem widgetcommon.IWidgetItem)
			AddChildFun = func(parentTreeNodeInfo *TreeNodeInfo, parentWidgetItem widgetcommon.IWidgetItem) {
				parentWidgetItem.ForEach(func(wItemChild widgetcommon.IWidgetItem) bool {
					// 将对象指针转换为字符串
					ptrAsString := fmt.Sprintf("%p", wItemChild)
					nodeObj := &TreeNodeInfo{
						id:          id,
						ptrAsString: ptrAsString,
						name:        wItemChild.GetName(),
						node:        wItemChild,
					}
					if wItemChild.IsContainer() {
						nodeObj.branch = true
					}
					AddChildFun(nodeObj, wItemChild)
					parentTreeNodeInfo.child = append(parentTreeNodeInfo.child, nodeObj)
					parentTreeNodeInfo.childName = append(parentTreeNodeInfo.childName, nodeObj.name)
					parentTreeNodeInfo.childObjName = append(parentTreeNodeInfo.childObjName, ptrAsString)
					allTreeMap[ptrAsString] = nodeObj
					return false
				})
			}
			AddChildFun(nodeRootObj, widgetItem)
			allTreeMap[ptrRootAsString] = nodeRootObj
			allTreeMap[""] = nodeRootObj
			return nodeRootObj.childObjName
		} else {
			return []widget.TreeNodeID{}
		}
	}
	e.treeRoot.ChildUIDs = fn
	fn2 := func(id widget.TreeNodeID) bool {
		if id == "" {
			return true
		}
		obj, ok := allTreeMap[id]
		if !ok {
			return false
		}
		if obj.branch {
			return true
		}
		return false
	}
	e.treeRoot.IsBranch = fn2
	fn3 := func(branch bool) fyne.CanvasObject {
		if branch {
			return widget.NewLabel("1")
		}
		return widget.NewLabel("2")
	}
	e.treeRoot.CreateNode = fn3
	fn4 := func(id widget.TreeNodeID, branch bool, o fyne.CanvasObject) {
		//text := id
		text := ""
		obj, ok := allTreeMap[id]
		if !ok {
			return
		}
		text = obj.name
		obj.treeNode = o
		if branch {
			text += "（+）" // 父节点
			o.(*widget.Label).SetText(text)
		} else {
			o.(*widget.Label).SetText(text)
		}
	}
	e.treeRoot.UpdateNode = fn4
	// 处理节点点击事件
	e.treeRoot.OnSelected = func(id widget.TreeNodeID) {
		if !e.treeRoot.IsBranch(id) {
			obj, ok := allTreeMap[id]
			if !ok {
				return
			}

			// 调用双击回调函数，跳转到属性面板
			if e.onNodeDoubleClicked != nil {
				e.onNodeDoubleClicked(obj.node)
			}
		}
	}

	// 刷新 treeRoot
	e.treeRoot.Refresh()
}
